<template>
  <div class="subcontract-registration-manage">
    <div v-if="!showSonList">
      <div class="model-title-css">
        合同登记
      </div>
      <div class="background_wrap">
        <div class="operate_wrap">
          <div class="leftBox">
            <el-button type="primary" size="small" class="add buildButtonStyle" v-permission="permission.add" round @click="showDialog('build', '合同新增')"><i class="iconfont icon-icon_add"></i> 新增合同
            </el-button>
          </div>
          <!--  -->
          <div class="rightBox flex-right">
            <el-select class="select" size="small" v-model="search.projectId" clearable filterable @change="onSearch" placeholder="选择项目">
              <el-option v-for="(item,index) in projectTree" :key="index" :label="item.name" :value="item.id">
              </el-option>
            </el-select>

            <el-select class="select" size="small" v-model="search.searchType" placeholder="合同类型" clearable @change="onSearch">
              <el-option v-for="(item,index) in typeOptions" :key="index" :label="item.label" :value="item.value">
              </el-option>
            </el-select>

            <el-input class="input" size="small" v-model="search.searchName" placeholder="请输入合同名称" clearable @change="onSearch"></el-input>

            <el-button class="search" size="small" @click="onSearch">
              <i class="iconfont icon-sousuo"></i>&nbsp;搜索
            </el-button>
          </div>
        </div>

        <div class="list_wrap">
          <el-table class="table-three-blue auto-flex-table" :border="true" :row-class-name="tableRowStyleName" :cell-class-name="tableCellStyleName" :header-cell-class-name="tableHeaderCellStyleName" :stripe="true" ref="multipleTable" :data="list" tooltip-effect="dark" @cell-click="cellClick" style="width: 100%; font-family: PingFangSC-Regular; font-size: 14px">
            <el-table-column show-overflow-tooltip align="center" label="序号" width="60" type="index">
              <template slot-scope="scope">
                {{ search.pageNo * search.pageSize + scope.$index +  + 1 }}
              </template>
            </el-table-column>

            <el-table-column show-overflow-tooltip v-for="(item, i) in elTableList" :key="i" :sortable="item.sort? item.sort : false" :width="item.width" :prop="item.prop" :formatter="formatter" :label="item.name">
            </el-table-column>

            <el-table-column show-overflow-tooltip prop="orderDate" width="120" label="签订日期">
            </el-table-column>

            <el-table-column show-overflow-tooltip prop="quantity" width="160" label="合同总额(万元)">
              <template slot-scope="scope">
                <div style="text-align:right;">
                  <!-- {{ scope.row.amount | moneyFilter }} -->
                  {{scope.row.amount}}
                </div>
              </template>
            </el-table-column>

            <el-table-column show-overflow-tooltip label="操作" width="250" fixed="right">
              <template slot-scope="scope">
                <el-button size="mini" class="menu_icon iconfont icon-icon_look action_color1" v-permission="permission.show" @click="showDialog('check','合同审批信息查看',scope.row.id)">&nbsp;查看</el-button>
                <el-button size="mini" class="menu_icon iconfont icon-xiugai-copy action_color1" v-permission="permission.edit" @click="showDialog('edit','合同审批信息编辑',scope.row.id)">&nbsp;修改</el-button>
                <el-button size="mini" class="menu_icon iconfont icon-shanchu action_color2" v-permission="permission.del" @click="showDialog('delete','删除',scope.row.id)">&nbsp;删除</el-button>
                <!--  <el-button size="mini" class="menu_icon iconfont icon-ren1 action_color3" v-if="scope.row.projectId" v-permission="permission.per" @click="showDialog('person','履约人员维护',scope.row.id)">&nbsp;履约人员维护</el-button>-->
              </template>
            </el-table-column>
          </el-table>
          <el-pagination style="float: right; margin-top: 30px" layout="prev, pager, next" :page-size="search.pageSize" :total="search.total" :current-page="search.pageNo + 1" :prev-text="tablePaginationPrev" :next-text="tablePaginationNext" @current-change="paginationChange">
          </el-pagination>
        </div>
      </div>
    </div>

    <Detail :postDetail="postDetailData" @reloadList="getList(true)"></Detail>
    <ListSon @closeList="showSonList = false" :postSon="postSonData"></ListSon>

  </div>
</template>

<script>
import {
  tableRowStyleGol,
  tableCellStyleGol,
  tableHeaderCellStyleGol,
} from '@/utils/publicFun'

import crudDict from '@/api/system/dict'
import msgUtil from '@/utils/msgUtil'
import projectSectionInfo from '@/api/buss/common'
import contract from '@/api/buss/contract'

import publicSearchData from '@/mixins/publicSearchData'
export default {
  mixins: [publicSearchData],
  name: `contractInitiation`,
  components: {
    ListSon: require('./sonList/sonList').default,
    Detail: require(`./contractInitiation-detail/contractInitiation-detail`).default,
  },
  data() {

    return {
      showSonList: false,
      permission: {
        add: ['100', 'contract:add'],
        show: ['100', 'contract:show'],
        edit: ['100', 'contract:edit'],
        del: ['100', 'contract:del'],
        per: ['100', 'contract:personDeal'],
      },

      tableRowStyleName: tableRowStyleGol,
      tableCellStyleName: tableCellStyleGol,
      tableHeaderCellStyleName: tableHeaderCellStyleGol,
      tablePaginationPrev: '上一页',
      tablePaginationNext: '下一页',
      hasAdd: false, //是否有新增权限
      loading: false,
      //  当前查看的文件列表
      nowFileList: [],
      showFileDialog: false,
      list: [],
      processDialog: false,
      rowId: '', //生成二维码所需要的id
      description: '二维码描述信息',
      projectUrl: '',
      addCan: false, //是否有新增权限
      title: '人员',
      inputNums: '',
      selectStatus: '',
      options: [],
      showSelectDialog: false,
      bdList: [],
      selectValue: '',
      // 搜索参数
      search: {
        subcontractName: '',
        //pageIndex: 0,
        pageNo: 0,
        pageSize: 10,
        //pageSum: 0,
        total: 0,
        contractId: '',
        searchType: '', // 合同类型
        searchName: '', // 合同名称
        company: { children: [] },
        companyId: '',
        project: { children: [] },
        sectionId: '',
      },

      typeOptions: [
        {
          label: '合同分类',
          value: '',
        },
      ],

      // 向详情子组件的传值
      postDetailData: {
        show: false,
        type: 'build',
        typeName: '新增',
      },
      postSonData: {
        show: false,
        type: 'build',
        typeName: '新增',
      },
      allowSelContract: false,
      //  选择的工程类合同-施工
      contractId: [],
      contract: null,
      // el的table列表
      elTableList: [
        {
          name: '项目名称',
          prop: 'projectName',
          width: '150'
        },
        {
          name: '合同编号',
          prop: 'number',
          width: '150',
        },
        {
          name: '合同分类',
          prop: 'contractTypeName',
          width: '150',
        },
        {
          name: '合同名称',
          prop: 'title',
          width: '450',
        },
        {
          name: '合同签订单位(乙方)',
          prop: 'secondPartyNoRelationName',
          width: '220'
        }
      ], // el的table列表
      routerData: {
        projectId: '',
        type: '',
      },
      companyTree: [],
      projectTree: [],
      companyListFiltered: [],
      companyListFilteredIdMap: {},
    }
  },

  created() {
    // this.initData()
    //this.getList()
  },

  mounted() {
    if (this.$route.query != undefined) {
      this.routerData = this.$route.query
      this.search.searchType = this.routerData.type
      this.getList(true)
      this.initData()
    }
  },
  methods: {
    onSearch() {
      this.search.pageNo = 0
      this.search.total = 0
      this.getList(true)
    },
    initData() {
      this.typeOptions = []
      this.companyTree = []
      crudDict.getByCode('contractType').then(res => {
        if (res.code === 200) {
          var data = res.data;
          for (var i in data) {
            this.typeOptions.push({ 'value': data[i].id, 'label': data[i].name });
          }
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取问题归属失败")
      })


      projectSectionInfo.getProjSecTreeAll().then(res => {
        if (res.code === 200) {
          // console.log(res)
          this.$set(this, 'projectTree', res.data)
          if (this.$headerSearch) {
            this.$set(this.search, 'projectId', this.changeHeaderProject)
            this.getList(true)
          }
        } else {
          this.$messageError(res.data.message)
        }
      }).catch(() => {
        this.$messageError('获取项目标段树失败')
      })

    },

    fixQueryA() {
      if (this.search.project) {
        this.search.project = {}
      }
      this.companyTree.forEach((item) => {
        if (item.id === this.search.company.id) {
          this.projectTree = item.children
          if (this.projectTree.length > 0) {
            if (!this.routerData.projectId) {
              // this.search.project.id = this.projectTree[0].id;
            } else {
              this.projectTree.forEach((item, index) => {
                if (item.id == this.routerData.projectId) {
                  this.search.project = item
                }
              })
            }
            this.search.pageNo = 0;
            this.search.total = 0;
            this.getList();
          }
        }
      })
    },


    // 格式化表单数据
    formatter(row, column) {
      let array = column.property.split('.')
      let result
      array.forEach((item, i) => {
        result = result === undefined ? row[item] : result[item]
        if (item == 'type' && row[item] == 1) {
          result = '内部'
        } else if (item == 'type' && row[item] == 2) {
          result = '外部'
        }
      })
      if (result === '' || result === undefined) {
        return '--'
      } else {
        return result
      }
    },


    // 点击单元格
    cellClick(row, column, cell, event) {
      if (column.property === 'number') {
        this.showDialog('check', '合同审批查看', row.id)
      }
    },
    // 获取列表 api
    getList(reload) {
      if (reload) {
        this.search.pageNo = 0
      }
      if (this.routerData.projectId) {
        this.search.projectId = this.routerData.projectId
      }
      this.list = []
      let param = {
        pageNo: this.search.pageNo,
        pageSize: this.search.pageSize,
        projectId: this.search.projectId,
        contractType: this.search.searchType,
        title: this.search.searchName,
      }

      contract.getTablePage(param).then(res => {
        if (res.status == 1) {
          if (res.list.length > 0) {
            this.list = res.list
            this.list.forEach((item, index) => {
              // console.log(item)
              if (item.orderDate) {
                item.orderDate = item.orderDate.substring(0, 10)
              }
            })
          }
          this.search.total = res.total
        } else {
          msgUtil.error2(res.data.message)
        }
      })

    },


    getContract(val) {
      return contract.getOne(val).then(res => {
        if (res.status == 1) {

          return new Promise(reslove => {
            reslove(res.data)
          })

        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取详情信息失败")
      })

    },


    // 切换列表
    paginationChange(index) {
      this.search.pageNo = index - 1
      this.getList()
    },



    /*  操作 */
    showDialog(type, typeName, detailId) {
      switch (type) {
        case 'build':
          this.postDetailData = {
            show: true,
            type: type,
            typeName: typeName,
            detailId: '',
          }
          break
        case 'edit':
          this.postDetailData = {
            show: true,
            type: type,
            typeName: typeName,
            detailId: detailId,
          }
          break
        case 'check':
          this.postDetailData = {
            show: true,
            type: type,
            typeName: typeName,
            detailId: detailId,
          }
          break
        case 'person':

          //履约人员（XXXX公司 - XXXXXXX项目 - XXXX合同编号）
          this.getContract(detailId).then(item => {
            let title = ''
            if (item.projectName == undefined || item.projectName == '') {
              title = '履约人员（' + item.secondPartyNoRelationName + '-' + item.number + ')'
            } else {
              title = '履约人员（' + item.secondPartyNoRelationName + '-' + item.projectName + '-' + item.number + ')'
            }

            let projectId = item.projectId
            let projectName = item.projectName
            let companyName = item.secondPartyNoRelationName
            let contractName = item.title

            this.postSonData = {
              showList: true,
              detailId: detailId,
              title: title,
              projectId: projectId,
              companyName: companyName,
              projectName: projectName,
              contractName: contractName,
            }
            this.showSonList = true
          })
          break
        case 'delete':
          if (detailId === '') {
            msgUtil.error2('请先选择要删除的记录！')
            return
          }
          msgUtil.confirm('确认删除该条数据?').then(res => {
            let idlist = []
            idlist.push(detailId)
            let param = {
              ids: idlist
            }
            contract.del(param).then(res => {
              if (res.status === 1) {
                msgUtil.success2('删除成功!')
                this.getList()
              } else {
                msgUtil.error2(res.data.message)
              }
            })
          })
          break

      }
    },


    //  获取合同类型 api
    getContractTypeList() {
      this.$httpPost('' + '/japi/dict/valuelabel/newContractType')
        .then((res) => {
          if (res.data.status === 1) {
            this.typeOptions = [
              {
                label: '合同类型',
                value: '',
              },
            ]
            res.data.list.forEach((item) => {
              this.$set(this.typeOptions, this.typeOptions.length, item)
            })
          } else {
            this.$messageError(res.data.message)
          }
        })
        .catch((res) => {
          console.log('请求出现错误', res)
          this.$messageError(this.$route.name + '请求失败')
        })
    },


  },
}
</script>

<style scoped lang="scss">
.operate_wrap {
  height: 40px;
  width: 100%;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;

  .leftBox {
    display: flex;
    align-items: center;
  }

  .rightBox {
    display: flex;
    align-items: center;
  }

  .select {
    width: 150px;
    margin-right: 15px;
  }
  .input {
    width: 150px;
    margin-right: 15px;
  }
  .mr15 {
    margin-right: 15px;
  }
  .search {
    width: 88px;
    color: #fff;
    margin-left: 0 !important;
  }
}

.list_wrap {
  margin-top: 20px;
}
</style>
